package com.bicon.botu.mall.base.rpc.service;


import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.bicon.botu.core.base.common.Constants;
import com.bicon.botu.core.base.common.controller.BaseController;
import com.bicon.botu.core.base.common.entity.BaseResult;
import com.bicon.botu.mall.base.common.ValidationUtil;
import com.bicon.botu.mall.base.dto.ProductDTO;
import com.bicon.botu.mall.base.entity.FreightTemplate;
import com.bicon.botu.mall.base.service.IFreightTemplateService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 订单中商品计算运费
 *
 * @author liushujie
 * @date 2018/5/8 0008 下午 16:05
 */
@Service
public class FreightTemplateRpcService extends BaseController {

    @Autowired
    IFreightTemplateService iFreightTemplateService;

    /**
     * 根据订单商品属性信息计算运费
     *
     * 通过商品id从缓存中查询重量、体积、运费模板id
     * 根据收货地址id查询对应省份
     * 根据运费模板id查询所在省份的运费模板配送区域资费
     * 需要检查各项的数据类型。
     * @param  productJson 商品id(productId)、数量(number)
     * @param  addressId 收货地址id
     * @return
     */
    @RequestMapping(value = "/calc-freight", method = RequestMethod.POST)
    public BaseResult calcFreight(@RequestParam String productJson, @RequestParam String addressId) {
        if (StringUtils.isEmpty(productJson)) {
            return sendResult400("商品列表不能为空");
        }
        if (StringUtils.isEmpty(addressId)) {
            return sendResult400("用户收货地址id不能为空");
        }
        List<ProductDTO> userInfos = JSONArray.parseArray(productJson, ProductDTO.class);
        if(ValidationUtil.isEmpty(userInfos)){
            return sendResult400("商品列表不能为空");
        }
        return sendResult(Constants.RESPONSE_CODE_200, Constants.RESPONSE_MESSAGE_200, iFreightTemplateService.calcFreight(userInfos,addressId));
    }


    /**
     * 获取已启用的运费模板
     * @return
     */
    @RequestMapping(value = "/enabled-list", method = RequestMethod.GET)
    public BaseResult enabled() {
        List<FreightTemplate> freightTemplateList = new FreightTemplate().selectList(new EntityWrapper<FreightTemplate>().eq("logic_delete", Constants.DEL_LOGIC_NORMAL).
                eq("enable", 0).orderBy("sort", false));
        return new BaseResult(Constants.RESPONSE_CODE_200, Constants.RESPONSE_MESSAGE_200, freightTemplateList);
    }
}
